//
//  MainIPhoneViewController.m
//  bsl-sdk
//
//  Created by Fanty on 13-12-2.
//
//

#import "CubeHomeIPhoneViewController.h"
#import "IsolatedStorageFile(CubePage).h"
#import "SVProgressHUD.h"
#import <ChamleonSDK/CApplication.h>
#import "CubeModule.h"
#import "CubeModuleManager.h"
#import "BSLCubeConstant.h"
#import "DataCenter+Cube.h"
#import "CubesModel.h"
#import "KKProgressToolbar.h"
#import "JSUtils.h"
#import "CubeLandingViewController.h"
#import "CubeWebViewController.h"

#define ALERT_TAG_DOWNLOADING    11000
#define ALERT_TAG_UPDATING       11001

@interface CubeHomeIPhoneViewController ()<AutoDownloadCheckingOperatorDelegate,UIAlertViewDelegate,KKProgressToolbarDelegate>
-(void)cubeModuleWeb:(NSNotification*)notification;
-(void)cubeSyncStart:(NSNotification*)notification;
-(void)cubeModuleUpdateIconNumber:(NSNotification*)notification;
-(void)moduleMainRedirectManager:(NSNotification*)notification;
-(void)moduleMainRedirectMain:(NSNotification*)notification;
-(void)cubeModuleRunningLanding:(NSNotification*)notification;
-(void)cubeSyncSuccess:(NSNotification*)notification;
-(void)cubeSyncFailed:(NSNotification*)notification;
-(void)cubeModuleDownloadingProcess:(NSNotification*)notification;
-(void)cubeModuleDownloadingSuccess:(NSNotification*)notification;
-(void)cubeModuleDownloadingFailed:(NSNotification*)notification;
-(void)cubeRefreshModule:(NSNotification*)notification;
-(void)cubeRefreshMainPage:(NSNotification*)notification;
-(void)cubeReceiveMessage:(NSNotification*)notification;
-(void)cubeUpdateProgress:(NSNotification*)notification;
-(void)cubeSettingPage:(NSNotification*)notification;


-(void)updateIconNumber;
-(void)updateAutoProgress;
-(void)showProgress:(BOOL)show;

@end

@implementation CubeHomeIPhoneViewController

-(id)init{
    self=[super init];
    
    if(self){
        CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];

        autoDownloadCheckingOperator=module.autoDownloadCheckingOperator;
        autoDownloadCheckingOperator.delegate=self;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleWeb:) name:CubeModuleWeb object:nil];
        

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeSyncStart:) name:CubeSyncStart object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleUpdateIconNumber:) name:CubeModuleUpdateIconNumber object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moduleMainRedirectManager:) name:ModuleMainRedirectManager object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moduleMainRedirectMain:) name:ModuleMainRedirectMain object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleRunningLanding:) name:CubeModuleRunningLanding object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeSyncSuccess:) name:CubeSyncSuccess object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeSyncFailed:) name:CubeSyncFailed object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleDownloadingProcess:) name:CubeModuleDownloadingProcess object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleDownloadingSuccess:) name:CubeModuleDownloadingSuccess object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeModuleDownloadingFailed:) name:CubeModuleDownloadingFailed object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeRefreshModule:) name:CubeRefreshModule object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeRefreshMainPage:) name:CubeRefreshMainPage object:nil];

        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeReceiveMessage:) name:CubeReceiveMessage object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeUpdateProgress:) name:CubeUpdateProgress object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cubeSettingPage:) name:CubeSettingPage object:nil];
    }
    
    return self;
}

- (void)viewDidLoad{
    
    
    //加载本地已经下载的模块
    CubeModule* module=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];
    
    [module.cubeModuleManager loadLocalModuleList];
    
    NSURL* url=[NSURL fileURLWithPath:[IsolatedStorageFile cordovaMainDirectory]];
    [self loadFilePageWithFileUrl:url];
    [super viewDidLoad];

    

    CGRect rect=self.view.frame;
    rect.size.height-=20.0f;
    self.view.frame=rect;
    
    rect=self.webView.frame;
    rect.size.height=self.view.bounds.size.height-20.0f;
    self.webView.frame=rect;
    
    

    statusToolbar = [[KKProgressToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 44.0f)];
    statusToolbar.actionDelegate = self;
    [self.view addSubview:statusToolbar];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    autoDownloadCheckingOperator.delegate=nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark method

-(void)cubeModuleWeb:(NSNotification*)notification{
    NSString* identifier=notification.object;
    
    DataCenter* dataCenter=[DataCenter defaultCenter];
    CubeModel* model = [dataCenter finidInstallCubeModule:identifier];
    
    if([model.local length]>0){
        //本地模块
        return;
    }
    
    if (model.status == CubeMoudleStatusInstalling || model.status == CubeMoudleStatusUpdating){
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@ 正在下载中，请等待!",model.name] message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    if ([model.local length] > 0){
        NSArray* localModules = dataCenter.localModules;
        for (LocalModel* localModule in localModules){
            if([localModule.identifier isEqualToString:identifier]){
                //跳转去原生模块
                [[CApplication sharedApplication] redirectToModulePage:identifier params:nil];
                break;
            }
        }
        
    }
    else{
        CubeModule* cubeDataModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];

        NSArray* dependsOnModules=[cubeDataModule.autoDownloadCheckingOperator dependsList:identifier];
        if([dependsOnModules count]>0){
            BOOL first = YES;
            NSMutableString* builder=[[NSMutableString alloc] initWithCapacity:2];
            
            for (DependsOnModule* _model in dependsOnModules){
                NSString* _identifier = _model.identifier;
                CubeModel* cubeModel = [dataCenter finidInstallCubeModule:_identifier];
                if (cubeModel == nil){
                    cubeModel = [dataCenter finidServiceCubeModule:_identifier];
                    if (cubeModel != nil){
                        //要下载依赖模块
                        [cubeDataModule.cubeModuleManager installModule:_identifier];
                        if (first){
                            first = NO;
                            [builder appendString:@"缺少以下依赖模块:\n"];
                        }
                        [builder appendFormat:@"%@\n",cubeModel.name];
                    }
                }
                else if (cubeModel.status == CubeMoudleStatusInstalling || cubeModel.status == CubeMoudleStatusUpdating){
                    cubeModel = [dataCenter finidServiceCubeModule:_identifier];
                    if (cubeModel != nil){
                        //要下载依赖模块
                        [cubeDataModule.cubeModuleManager installModule:_identifier];
                        if (first){
                            first = NO;
                            [builder appendString:@"缺少以下依赖模块:\n"];
                        }
                        [builder appendFormat:@"%@正在下载中...\n",cubeModel.name];

                    }
                }
            }
            
            first = YES;
            
            for (DependsOnModule* _model in dependsOnModules){
                NSString* _identifier = _model.identifier;
                //int _build = a.Value;
                CubeModel* cubeModel = [dataCenter finidInstallCubeModule:_identifier];
                if (cubeModel != nil && cubeModel.build < _model.build){
                    //要下载依赖模块
                    [cubeDataModule.cubeModuleManager installModule:_identifier];
                    if (first){
                        first = NO;
                        [builder appendString:@"需要更新以下依赖模块:\n"];
                    }
                    [builder appendFormat:@"%@\n",cubeModel.name];
                }
            }
            
            if ([builder length] > 2){
                UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:builder message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
                return;
            }
        }
    }
    
    //跳转到模块内部
//    [[BSLApplication sharedApplication] redirectToModulePage:identifier params:nil];
    
    CubeWebViewController* controller=[[CubeWebViewController alloc] init];
    controller.identifier=identifier;
    controller.rootViewController=self;
    [self.navigationController pushViewController:controller animated:YES];

    
}

-(void)cubeSyncStart:(NSNotification*)notification{
    [SVProgressHUD showWithStatus:@"模块加载中..." maskType:SVProgressHUDMaskTypeBlack];

}

-(void)cubeModuleUpdateIconNumber:(NSNotification*)notification{
    [self updateIconNumber];
}

-(void)moduleMainRedirectManager:(NSNotification*)notification{
    
}

-(void)moduleMainRedirectMain:(NSNotification*)notification{
    
}

-(void)cubeModuleRunningLanding:(NSNotification*)notification{
    
    NSArray* array=notification.object;
    
    NSString* identifier = [array objectAtIndex:0];
    NSString* action=[array objectAtIndex:1];
    int type=0;
    if ([action isEqualToString:@"uninstall"]){
        type = 0;
    }
    else if ([action isEqualToString:@"install"]){
        type = 1;
    }
    else{
        type = 2;
    }
    
    CubeLandingViewController* controller=[[CubeLandingViewController alloc] init];
    controller.type=type;
    controller.identifier=identifier;
    [self.navigationController pushViewController:controller animated:YES];
}

-(void)cubeSyncSuccess:(NSNotification*)notification{
    [SVProgressHUD dismiss];
    [autoDownloadCheckingOperator start];
    [self updateIconNumber];

}
-(void)cubeSyncFailed:(NSNotification*)notification{
    [SVProgressHUD dismiss];
    UIAlertView* alert=[[UIAlertView alloc] initWithTitle:@"暂未能成功获取最新模块信息" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];

}
-(void)cubeModuleDownloadingProcess:(NSNotification*)notification{
    [self updateAutoProgress];
}
-(void)cubeModuleDownloadingSuccess:(NSNotification*)notification{
    [self updateAutoProgress];

}
-(void)cubeModuleDownloadingFailed:(NSNotification*)notification{
    [self updateAutoProgress];

}
-(void)cubeRefreshModule:(NSNotification*)notification{
    
    NSDictionary* data=notification.object;

    if([data objectForKey:@"identifier"]!=nil && [data objectForKey:@"type"]!=nil && [data objectForKey:@"moduleMessage"]!=nil){
        NSString* identifier = [data objectForKey:@"identifier"];
        NSString* type = [data objectForKey:@"type"];
        NSString* moduleMessage = [data objectForKey:@"moduleMessage"];
        [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils refreshModule:identifier type:type moduleMessage:moduleMessage]];
    }
}
-(void)cubeRefreshMainPage:(NSNotification*)notification{
    NSDictionary* data=notification.object;
    
    if([data objectForKey:@"identifier"]!=nil && [data objectForKey:@"type"]!=nil && [data objectForKey:@"moduleMessage"]!=nil){
        NSString* identifier = [data objectForKey:@"identifier"];
        NSString* type = [data objectForKey:@"type"];
        NSString* moduleMessage = [data objectForKey:@"moduleMessage"];
        [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils refreshMainPage:identifier type:type moduleMessage:moduleMessage]];
    }

}
-(void)cubeReceiveMessage:(NSNotification*)notification{
    
    NSDictionary* data=notification.object;
    
    if([data objectForKey:@"identifier"]!=nil && [data objectForKey:@"count"]!=nil ){
        NSString* identifier = [data objectForKey:@"identifier"];
        NSString* count = [data objectForKey:@"count"];
        [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils receiveMessage:identifier count:[count intValue]]];
    }
    
}
-(void)cubeUpdateProgress:(NSNotification*)notification{
    NSDictionary* data=notification.object;
    
    if([data objectForKey:@"identifier"]!=nil && [data objectForKey:@"count"]!=nil ){
        NSString* identifier = [data objectForKey:@"identifier"];
        NSString* count = [data objectForKey:@"count"];
        [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils updateProgress:identifier count:[count intValue]]];
    }
}

-(void)cubeSettingPage:(NSNotification*)notification{
    
}



-(void)updateIconNumber{
    NSArray* mainListModules=[DataCenter defaultCenter].mainListModules;
    for (CubeModel* model in mainListModules){
        BOOL showMessage = (model.moduleBadge || [model.identifier isEqualToString:@"com.foss.message.record"] || [model.identifier isEqualToString:@"com.foss.announcement"]);
        [self.webView stringByEvaluatingJavaScriptFromString:[JSUtils receiveMessage:model.identifier count:( showMessage? model.messageCount : 0)]];
    }
}


-(void)updateAutoProgress{
    if (autoDownloadCheckingOperator.autoDownloadedCount > 0){
        CubeModule* cubeDataModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];
        
        int currentDownloadedCount=autoDownloadCheckingOperator.autoDownloadedCount-[cubeDataModule.cubeModuleManager downloadCount];
        int totalCount=autoDownloadCheckingOperator.autoDownloadedCount;
        
        statusToolbar.statusLabel.text = [NSString stringWithFormat:@"已下载%d,总计需下载:%d",currentDownloadedCount, totalCount];
        
        statusToolbar.progressBar.progress = ((float)currentDownloadedCount/(float)totalCount);
        
        
        if ([cubeDataModule.cubeModuleManager downloadCount]<1){
            autoDownloadCheckingOperator.autoDownloadedCount = 0;
            [self showProgress:NO];
        }
    }
}

-(void)showProgress:(BOOL)show{
    if(show)
        [statusToolbar show];
    else
        [statusToolbar hide];
    
    [UIView animateWithDuration:0.4 animations:^{
        CGRect rect=self.webView.frame;
        rect.size.height=(show?self.view.bounds.size.height-20.0f-statusToolbar.frame.size.height:self.view.bounds.size.height-20.0f);
        self.webView.frame=rect;
        
        rect=statusToolbar.frame;
        rect.origin.y=(show?self.view.bounds.size.height-20.0f-rect.size.height:self.view.bounds.size.height);
        statusToolbar.frame=rect;
    } completion:^(BOOL finished) {
    }];
}


#pragma mark autodownloadcheckingOperator delegate


-(void)autoSaveDidShowAutoDownloading:(AutoDownloadCheckingOperator*)cubeModuleAutoSaveParser message:(NSString*)message{
    UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"下载", nil];
    alertView.tag=ALERT_TAG_DOWNLOADING;
    [alertView show];
}

-(void)autoSaveDidShowUpdating:(AutoDownloadCheckingOperator*)cubeModuleAutoSaveParser message:(NSString*)message{
    UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"下载", nil];
    alertView.tag=ALERT_TAG_UPDATING;
    [alertView show];

}


#pragma mark alertview delegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(buttonIndex==1){
        
        statusToolbar.statusLabel.text = [NSString stringWithFormat:@"已下载%d,总计需下载:%d",0, autoDownloadCheckingOperator.autoDownloadedCount];
        statusToolbar.progressBar.progress = 0.0f;
        
        [self showProgress:YES];
        
        CubeModule* cubeDataModule=(CubeModule*)[[CApplication sharedApplication] moduleForIdentifier:@"bsl.cube"];
        
        for (CubeModel* cubeModel in autoDownloadCheckingOperator.downloadModels){
            if(alertView.tag==ALERT_TAG_DOWNLOADING){
                [cubeDataModule.cubeModuleManager installModule:cubeModel.identifier];
            }
            else{
                [cubeDataModule.cubeModuleManager updateModule:cubeModel.identifier];
            }
        }
        
    }
    
    [autoDownloadCheckingOperator clear];
}



@end
